package org.simplextensions.ui.menu;

import org.simplextensions.ui.SwingApplicationWindow;

import javax.swing.*;

public class WindowMenuManager extends MenuManager {

	private final SwingApplicationWindow applicationWindow;
	private final String menuId;

	private JMenuBar menuBar;

	public WindowMenuManager(SwingApplicationWindow applicationWindow, String menuId) {
		super(applicationWindow.getExtensionRegistry());
		this.applicationWindow = applicationWindow;
		this.menuId = menuId;

		this.applicationWindow.getjFrame().setJMenuBar(getMenuBar());

	}

	public JMenuBar getMenuBar() {
		if (menuBar == null) {
			MenuExtensionMetadata menu = getMep().getMenu(menuId);
			menuBar = new JMenuBar();

			for (MenuExtensionMetadata memd : menu.getSubItems()) {
				JMenu createdSubMenu = createMenu(memd);
				if (createdSubMenu != null) {
					menuBar.add(createdSubMenu);
				}
			}
		}
		return menuBar;
	}

	protected JMenuItem createMenuItems(MenuExtensionMetadata submemd, JMenu parentMenu, IActions executable) {
		JMenuItem createActions = super.createMenuItems(submemd, parentMenu, executable);
		if (executable instanceof IApplicationWindowActions) {
			((IApplicationWindowActions) executable).init(applicationWindow);
		}
		return createActions;
	}

	protected JMenuItem createMenuItem(final MenuExtensionMetadata submemd, final IAction executable) {
		JMenuItem createMenuItem = super.createMenuItem(submemd, executable);
		if (executable instanceof IApplicationWindowAction) {
			((IApplicationWindowAction) executable).init(applicationWindow);
		}
		return createMenuItem;
	}
}